package com.siyoumi.app.sys.wxapp;

import com.siyoumi.app.entity.WxUserInfo;
import com.siyoumi.app.modules.account.service.SvcAccount;
import com.siyoumi.app.modules.account.vo.VoAdminLogin;
import com.siyoumi.app.modules.app_book.service.SvcBookOrder;
import com.siyoumi.app.modules.app_book.vo.VoBookOrderRefundApply;
import com.siyoumi.app.sys.service.CommonApiServcie;
import com.siyoumi.app.sys.service.WxApiService;
import com.siyoumi.app.sys.service.web_oauth.WebOauth;
import com.siyoumi.app.sys.vo.*;
import com.siyoumi.component.XRedis;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.config.SysConfig;
import com.siyoumi.controller.WxAppApiController;
import com.siyoumi.entity.SysLog;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.service.SysLogService;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XFile;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//小程序通用接口
@Slf4j
@RestController
@RequestMapping("/wxapp/app/api")
public class ApiWxapp
        extends WxAppApiController {

    @PostMapping("/phone_login")
    @Transactional(rollbackFor = Exception.class)
    public XReturn phoneLogin(@Validated PhoneLoginVo data, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true, true);

        data.setOpenid(getOpenid());


        if ("yituky".equals(XHttpContext.getX())) {
            data.setAuto_reg(true);
        }
        if (SysConfig.getBean().isDev()) {
            //data.setAuto_reg(true);
        }

        return WxApiService.getBean().phoneLogin(data);
    }

    /**
     * 扫码确认登陆
     *
     * @param vo
     * @param result
     */
    @PostMapping("/sacn_login")
    public XReturn scanLogin(@Validated ScanLoginVo vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true, true);

        String val = XRedis.getBean().get(ScanLoginVo.redisKey(vo.getKey()));
        if (XStr.isNullOrEmpty(val)) {
            return EnumSys.ERR_VAL.getR("key已失效");
        }
        if (!"0".equals(val)) {
            return EnumSys.OK.getR("已操作");
        }

        XReturn tokenData = XReturn.getR(0);
        tokenData.setData("timestamp", XDate.toMs());
        tokenData.setData("x", XHttpContext.getX());
        tokenData.setData("uid", getUid());
        tokenData.setData("openid", getOpenid());
        String jwtToken = WxApiService.getBean().getToken(tokenData);
        String webToken = WebOauth.getIns(XHttpContext.getX()).getWebToken(jwtToken);
        //授权成功
        XRedis.getBean().setEx(ScanLoginVo.redisKey(vo.getKey()), webToken, 3 * 60);

        return getR();
    }

    /**
     * 退出登陆
     */
    @PostMapping("/phone_logout")
    public XReturn phoneLogout() {
        return WxApiService.getBean().phoneLogout(getOpenid());
    }

    /**
     * 登陆商家后台
     *
     * @param vo
     * @param result
     */
    @PostMapping("/admin_login")
    @Transactional(rollbackFor = Exception.class)
    public XReturn adminLogin(@Validated @RequestBody VoAdminLogin vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true);

        return SvcAccount.getBean().adminLogin(vo);
    }

    @GetMapping({"/get_phone", "/getPhone"})
    public XReturn getPhone() {
        String code = input("code");
        return WxApiService.getBean().getPhone(code);
    }


    @PostMapping({"/upload_img"})
    @SneakyThrows
    public XReturn uploadImg(@Validated VoUploadFile vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true, true);

        List<String> ex = XFile.getImgExtenstions();
        return CommonApiServcie.getBean().uploadFile(vo, ex);
    }

    @PostMapping({"/upload_file"})
    public XReturn uploadFile(@Validated VoUploadFile vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true, true);

        List<String> ex = XFile.getFileExtenstions();
        return CommonApiServcie.getBean().uploadFile(vo, ex);
    }

    @RequestMapping("/user_edit")
    public XReturn userEdit(WxUserInfo entityWxUserInfo) {
        return WxApiService.getBean().userEdit(entityWxUserInfo);
    }

    @PostMapping("/user_update")
    public XReturn userUpdate(@Validated() VaWxUser vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true, true);

        return WxApiService.getBean().userUpdate(vo);
    }

    /**
     * 添加临时数据
     */
    @PostMapping("add_temp_data")
    public XReturn addTempData(@Validated @RequestBody VoAddTempData vo, BindingResult result) {
        //
        XValidator.getResult(result, true, true);

        SysLog entityLog = SysLogService.getBean().addTempData(getUid(), vo.getText());
        XReturn r = XReturn.getR(0);
        r.setData("temp", entityLog);
        return r;
    }

    /**
     * 获取临时数据
     */
    @GetMapping("get_temp_data")
    public XReturn getTempData() {
        String tempId = input("temp_id");
        XValidator.isNullOrEmpty(tempId, "miss temp_id");

        SysLog entityLog = SysLogService.getBean().getEntity(tempId);
        XValidator.isNull(entityLog, "临时数据已失效");

        if (!entityLog.getLog_type().equals("temp")) {
            return EnumSys.ERR_VAL.getR("非临时数据");
        }

        XReturn r = XReturn.getR(0);
        r.setData("temp", entityLog);
        return r;
    }
}
